<template>
	<view class="user-created-poster">
		<view class="user-created-poster-box">
			<canvas id="poster" class="poster-canvas" canvas-id="poster" style="width: 535rpx; height: 1000rpx;"
				v-if="!show"></canvas>
			<image :src="imgUrl" style="width: 535rpx; height: 1000rpx;" v-else></image>
			<view class="user-created-poster-btn">
				<image src="https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/images/shop/icons/my/save.png" mode="widthFix"
					@click="save"></image>
			</view>
		</view>
		<pt-openSetting ref="openSetting" tips="您已关闭相册访问开关，请打开开关后重新保存"></pt-openSetting>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show: false,
				image: '',
				qrcode: '',
				imgUrl: ''
			};
		},
		onLoad(options) {
			this.image = options.url
			this.qrcode = options.qrcode
		},
		onShow() {
			this.$nextTick(() => {
				if (this.image && this.qrcode) {
					this.onCanvas()
				}
			})
		},
		methods: {
			async onCanvas() {
				let _this = this;
				_this.ctx = uni.createCanvasContext('poster', this);
				const systemInfo = uni.getSystemInfoSync();
				const image = await _this.getImageInfo({
					imgSrc: _this.image
				}); // 背景图
				const QRcodeImgInfo = await _this.getImageInfo({
					imgSrc: _this.qrcode
				}); // 二维码
				_this.canvasW = uni.upx2px(535);
				_this.canvasH = uni.upx2px(1000);

				_this.ctx.setFillStyle('#FFFFFF');
				_this.ctx.fillRect(0, 0, _this.canvasW, _this.canvasH)

				// 绘制背景图
				_this.ctx.drawImage(image.path, 0, 0, uni.upx2px(535), uni.upx2px(1000));

				// 绘制二维码
				_this.roundRectColor(_this.ctx, uni.upx2px(202.5), uni.upx2px(800), uni.upx2px(130), uni.upx2px(130), uni
					.upx2px(40));
				_this.ctx.drawImage(QRcodeImgInfo.path, uni.upx2px(210), uni.upx2px(807.5), uni.upx2px(115), uni.upx2px(115));
				_this.ctx.restore()

				//延迟后渲染至canvas上
				setTimeout(function() {
					_this.ctx.draw(false, () => {
						_this.createdImg()
					});
				}, 600);
			},
			async getImageInfo({
				imgSrc
			}) {
				uni.showLoading({
					title: '正在生成海报',
					mask: true
				})
				return new Promise((resolve, errs) => {
					if (imgSrc.indexOf('https') != -1) {
						uni.downloadFile({
							url: imgSrc,
							success: function(res) {
								uni.getImageInfo({
									src: res.tempFilePath,
									success: function(image) {
										uni.hideLoading()
										resolve(image);
									},
									fail(err) {
										uni.hideLoading()
										uni.showToast({
											title: '生成失败，请退出重试',
											icon: 'none',
											duration: 1500
										})
										errs(err);
									}
								});
							},
							fail: (aa) => {
								console.log(aa)
							}
						})
					} else {
						uni.getImageInfo({
							src: imgSrc,
							success: function(image) {
								uni.hideLoading()
								resolve(image);
							},
							fail(err) {
								uni.hideLoading()
								uni.showToast({
									title: '生成失败，请退出重试',
									icon: 'none',
									duration: 1500
								})
								errs(err);
							}
						});
					}
				});
			},
			async roundRectColor(context, x, y, w, h, r) { //绘制圆角矩形（纯色填充）
				context.save();
				context.setFillStyle("#FFF");
				context.setStrokeStyle('#FFF')
				context.setLineJoin('round'); //交点设置成圆角
				context.setLineWidth(r);
				context.strokeRect(x + r / 2, y + r / 2, w - r, h - r);
				context.fillRect(x + r, y + r, w - r * 2, h - r * 2);
				context.stroke();
				context.closePath();
			},
			createdImg() {
				uni.canvasToTempFilePath({
					destWidth: 535,
					destHeight: 1000,
					canvasId: 'poster',
					success: (data) => {
						this.imgUrl = data.tempFilePath
					},
					fail: (fail) => {
						console.log(fail)
					}
				})
			},
			save() {
				let _this = this
				uni.showLoading({
					title: '正在保存',
					mask: true
				})
				uni.canvasToTempFilePath({
					destWidth: 535,
					destHeight: 1000,
					canvasId: 'poster',
					success: (data) => {
						uni.hideLoading()
						// #ifdef APP-PLUS || H5
						uni.saveImageToPhotosAlbum({
							filePath: data.tempFilePath,
							success: () => {
								uni.showToast({
									icon: 'none',
									title: '保存成功，请在相册中查看',
									duration: 1500
								})
							},
							fail: (fail) => {
								uni.showToast({
									icon: 'none',
									title: '保存失败',
									duration: 1500
								})
							}
						})
						// #endif
						// #ifdef MP-WEIXIN
						uni.getSetting({
							withSubscriptions: true,
							success: (scope) => {
								if (!scope.authSetting['scope.writePhotosAlbum']) {
									uni.authorize({
										scope: 'scope.writePhotosAlbum',
										success: () => {
											uni.saveImageToPhotosAlbum({
												filePath: data.tempFilePath,
												success: () => {
													uni.showToast({
														icon: 'none',
														title: '保存成功，请在相册中查看',
														duration: 1500
													})
												},
												fail: (fail) => {
													uni.showToast({
														icon: 'none',
														title: '保存失败',
														duration: 1500
													})
												}
											})
										},
										fail: () => {
											// uni.showToast({
											// 	icon: 'none',
											// 	title: '您已关闭相册访问开关，请开启后重新保存'
											// })
											this.$refs.openSetting.init()
										}
									})
								} else {
									uni.saveImageToPhotosAlbum({
										filePath: data.tempFilePath,
										success: () => {
											uni.showToast({
												icon: 'none',
												title: '保存成功，请在相册中查看',
												duration: 1500
											})
										},
										fail: (fail) => {
											uni.showToast({
												icon: 'none',
												title: '保存失败',
												duration: 1500
											})
										}
									})
								}
							}
						})
						// #endif
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.user-created-poster {
		position: fixed;
		background-color: #141414;
		width: 100%;
		height: 100%;
		top: 0;
		left: 0;
	}

	.poster-canvas {
		// position: absolute;
		// left: 9999px;
	}

	.user-created-poster-box {
		text-align: center;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
	}

	.user-created-poster-btn {
		margin-top: 60rpx;

		image {
			width: 230rpx;
		}
	}
</style>